package com.zichong.wiki.controller;

import com.zichong.wiki.req.EbookQueryReq;
import com.zichong.wiki.req.EbookSaveReq;
import com.zichong.wiki.resp.CommonResp;
import com.zichong.wiki.resp.EbookQueryResp;
import com.zichong.wiki.resp.PageResp;
import com.zichong.wiki.service.EbookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/ebook")
public class EbookController {

    @Autowired
    private EbookService ebookService;

    /**
     * params e.g.:
     * /ebook/list
     * /ebook/list?name=v
     * /ebook/list?page=1&size=3
     */
    @GetMapping("/list")
    public CommonResp list(@Valid EbookQueryReq req) {
        // 开启校验规则, 对应的规则为类里的 @Max, @NotNull 等注解
        CommonResp<PageResp<EbookQueryResp>> resp = new CommonResp<>();
        PageResp<EbookQueryResp> list = ebookService.list(req);
        resp.setContent(list);

        return resp;
    }

    /**
     * params e.g.:
     * create:
     * {
     *     "description": "test",
     *     "docCount": 0,
     *     "viewCount": 0,
     *     "voteCount": 0,
     *     "name": "Oracle"
     * }
     *
     * update:
     * {
     *     "description": "test1",
     *     "id": 5,
     *     "docCount": 0,
     *     "viewCount": 0,
     *     "voteCount": 0,
     *     "name": "Oracle"
     * }
     */
    @PostMapping("/save")
    public CommonResp save(@Valid @RequestBody EbookSaveReq req) {
        // @RequestBody 表示 json 方式的(post)提交, 需要用该注解才能接收到
        // 如果是 form 表单的提交, 则直接参数即可, 不用任何注解
        CommonResp resp = new CommonResp<>();
        ebookService.save(req);

        return resp;
    }

    /**
     * params e.g.:
     * /ebook/delete/133135771585613824
     */
    @DeleteMapping("/delete/{id}")
    public CommonResp delete(@PathVariable Long id) {
        // @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中, 比如当前的 id
        CommonResp resp = new CommonResp<>();
        ebookService.delete(id);

        return resp;
    }

}
